package x.ovo.wechat.bot.plugin;

import lombok.NonNull;
import org.dromara.hutool.core.regex.ReUtil;
import org.dromara.hutool.core.text.StrUtil;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.MessageEvent;
import x.ovo.wechat.bot.core.message.SystemMessage;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

public class WelcomeListener extends EventListener<MessageEvent<SystemMessage>, SystemMessage> {

    private static final Pattern PATTERN = Pattern.compile("\"?(?<inviter>\\S+?)\"?邀请\"(?<user>.*)\"加入了群聊");

    public WelcomeListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull MessageEvent<SystemMessage> event, SystemMessage source) {
        return source.getContent().contains("加入了群聊");
    }

    @Override
    public boolean onEvent(@NonNull MessageEvent<SystemMessage> event, SystemMessage source) {
        String group = source.getFrom().getNickName();
        String inviter = ReUtil.get(PATTERN, source.getContent(), "inviter");
        inviter = "你".equals(inviter) ? this.context.getSession().getNickName() : inviter;
        String user = ReUtil.get(PATTERN, source.getContent(), "user");
        Map<String, String> config = this.plugin.getConfig();
        String s = Optional.ofNullable(config.get(group)).orElse(config.get("*"));
        if (StrUtil.isNotBlank(s)) {
            source.getFrom().sendMessage(StrUtil.formatByMap(s, Map.of("inviter", inviter, "user", user), false));
            return true;
        }
        return false;
    }
}
